package com.lottery.im.util;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import java.util.ArrayList;

public class FragmentManagerUtil {

  private FragmentManager mFragmentManager;
  private int mContainerViewId;
  /** Fragment切换数组 */
  private ArrayList<Fragment> mFragments;
  /** 当前选中的Tab */
  private int mCurrentTab = 0;

  public FragmentManagerUtil(FragmentManager fm, int containerViewId,
      ArrayList<Fragment> fragments) {
    this.mFragmentManager = fm;
    this.mContainerViewId = containerViewId;
    this.mFragments = fragments;
    initFragments();
  }

  /** 初始化fragments */
  private void initFragments() {

    if (!mFragments.get(0).isAdded()) {
      mFragmentManager.beginTransaction().add(mContainerViewId, mFragments.get(0)).commit();
    }
  }

  /** 界面切换控制 */
  public void setFragments(int index) {

    //if (index == mCurrentTab) {
    //  return;
    //}

    if (index >= mFragments.size()) {
      return;
    }

    FragmentTransaction ft = mFragmentManager.beginTransaction();

    if (!mFragments.get(index).isAdded()) {
      ft.add(mContainerViewId, mFragments.get(index));
    } else {
      ft.show(mFragments.get(index));
    }

    for (int i = 0; i < mFragments.size(); i++) {
      if (i != index && mFragments.get(i).isAdded()) {
        ft.hide(mFragments.get(i));
      }
    }

    ft.commit();

    mCurrentTab = index;
  }

  public int getCurrentTab() {
    return mCurrentTab;
  }

  public Fragment getCurrentFragment() {
    return mFragments.get(mCurrentTab);
  }
}